import {Component, OnInit, AfterViewInit, ViewChild} from '@angular/core';
import {OneOperationComponent} from "../../../widgets/one-operation/one-operation.component";
import {Router, ActivatedRoute} from "@angular/router";
import {OneDialogService} from "../../../widgets/one-dialog/one-dialog.service";
import {ResponseUtil} from "../../../util/response-util";
import {PageSubject} from "../../../util/page-subject";
import {Path} from "../../../portal/admin/admin-breadcrumb/breadcrumb";
import {API, MsgConstants} from "../../../constants/constants";
import {TableUtil} from "../../../util/table-util";
import {MsgResult} from "../../../models/msg-result";
import {MonitorService} from "./monitor.service";


declare var $;
declare  var moment;

@Component({
  selector: 'app-site-monitor',
  templateUrl: 'site-monitor.component.html'
})

export class SiteMonitorComponent implements OnInit,AfterViewInit {
@ViewChild(OneOperationComponent) operation: OneOperationComponent;

  siteMonitorId :Array<string> =[];

  snCodeArr :Array<string> =[];

  codMonitors;

  receiveTimeVal :string;

  receiveTimeDevVal :string;

  table;


  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private tableUtil: TableUtil,
    private dialogService: OneDialogService,
    private monitorService: MonitorService,
    private responseUtil:ResponseUtil,
    private pageSubject: PageSubject
  ) { }

  proxy = {
    "siteMonitorAdd": () => this.siteMonitorAdd(),
    "siteMonitorUpdate": () => this.siteMonitorUpdate(),
    "siteMonitorDelete": () => this.siteMonitorDelete(),
    "siteDevicePollutant": () => this.siteDevicePollutant(),
    'assignmentSite': ()=> this.assignmentSite(),
  }

  ngOnInit() {
    this.pushPage();
    this.loadSiteMonitor();
    this.initMonitorType();
    this.initTimeControlConfig();
    this.receiveTimeApplyLabel();
    this.receiveTimeDevApplyLabel();
  }

  ngAfterViewInit() {
    //操作函数代理
    this.operation.proxy = this.proxy;
  }

  /**
   *  生成面包屑
   */
  private pushPage() {
    let path = new Path("运维管理", null);
    this.pageSubject.pushPage("设备管理", "查询", path);
  }

  search(){
    this.table.bootstrapTable('refresh');
  }

  /**
   * 主题查询
   */
  loadSiteMonitor() {
    this.table = this.tableUtil.load("one_table_monitor", {
      columns: [
        {checkbox: true },
        {field: "id", title: 'ID', align: 'left', visible: false, switchable: false},
        {field: "siteCode", title: '站点代码', align: 'left', visible: false, switchable: false},
        {field: "siteName", title: '站点名称', align: 'left',class:"one-table-col-2"},
        {field: "snCode", title: '设备编号', align: 'left',class:"one-table-col-2"},
        {field: "monitorName", title: '设备类型', align: 'left',class:"one-table-col-4"},
        {field: "mPhone", title: '手机号', align: 'right', visible: false,class:"one-table-col-2"},
        { field: "ccid" ,title:'CCID',align:'left' ,class:"one-table-col-2"},
        {field: "receiveTime", title: '数据接收时间', align: 'left',class:"one-table-col-icon-6", sortName: "RECEIVETIME", sortable: true,formatter: this.tableUtil.showToolTip},
        {field: "receiveTime_Dev", title: '设备接收时间', align: 'left',class:"one-table-col-icon-6", sortName: "RECEIVETIME_DEV", sortable: true ,formatter: this.tableUtil.showToolTip},
        {field: "clientipinf", title: '通讯地址', align: 'left',class:"one-table-col-2"},
        {field: "status", title: '设备状态', align: 'left',class:"one-table-col-2", formatter: this.statusFormat},
        // { field: "remark",title:'说明' ,align:'left'},
        {field: "transMode", title: '数据传输方式', align: 'left',class:"one-table-col-6", formatter: this.yesOrNoFormat},
        {field: "arithmeticType", title: '数据算法模式', align: 'left',class:"one-table-col-6", formatter: this.arithmeticTypeFormat},
        {field: "location", title: '设备通讯地址', align: 'left', visible: false, class:"one-table-col-6"},
        {field: "parameter", title: '设备参数', align: 'left', visible: false, class:"one-table-col-2"},
        {field: "monitorStatus", title: '监控状态', align: 'left', visible: false, class:"one-table-col-2"},
        {field: "createDate", title: '创建日期', align: 'left',class:"one-table-col-2", sortName: "CREATEDATE", sortable: true ,visible: false},
        {field: "updateDate", title: '修改日期', align: 'left',class:"one-table-col-2", visible: false, sortName: "UPDATEDATE", sortable: true },
      ],
      idField: "id",
      sidePagination: 'server',
      pagination: true,
      pageNumber: 1,
      pageSize: 15,
      pageList: [10, 15, 50],
      paginationPreText: "上一页",
      paginationNextText: "下一页",
      paginationLoop: false,//是否开启循环分页
      singleSelect: false,//多选
      clickToSelect: true,//点击选中
      toolbar: "#one_operation_site-monitor",
      url: API.siteMonitorPageListV2,
      method: 'post',
      //传递附加参数
      queryParams: (params) => {
        params.siteName = $("#siteName").val();
        params.snCode = $("#snCode").val();
        params.monitorCode = $("#monitorCode").val();
        params.receiveTime = this.receiveTimeVal;
        params.receiveTimeDev = this.receiveTimeDevVal;
        params.status = $("#status").val();
        return params;
      },
      //返回数据处理器
      responseHandler: (result) => {
        return this.responseUtil.bsPageHandler(result, (result) => {
          result.data.rows.forEach(function (value) {
            value.createDate = value.createDate || '';
            value.updateDate = value.updateDate || '';
            value.receiveTime_Dev = value.receiveTimeDev || '-';
            value.receiveTime = value.receiveTime || '-';
          });
        });
      },
      height: 700,//table高度
      sortable: true,
      order: 'DESC',
      sortName: 'UPDATEDATE',
      undefinedText: '-',
      showColumns: true,//显示自定义显示列按钮
      showRefresh: true,//显示刷新按钮
      minimumCountColumns: 3,//最少保留显示的列数量
      showToggle: true,//显示视图切换按钮
      showPaginationSwitch: true,//显示是否分页切换按钮
      showExport: true,       //是否显示导出按钮
      exportDataType: 'all', //导出类型
      buttonsAlign: "right",  //按钮位置
      exportTypes: ['excel'],  //导出文件类型
      exportOptions: {
        ignoreColumn: [0],  //根据索引忽[0,1,2]略某一列的导出数据
        fileName: '设备数据报表',  //保存文件名称设置
        worksheetName: 'sheet1',  //表格工作区名称
        tableName: '设备数据报表',
        excelstyles: ['background-color', 'color', 'font-size', 'font-weight'],
      },
      classes: "table table-hover",
      striped: true,//隔行变色
      mobileResponsive: true//响应式
    });
    this.tableUtil.bindResetTableView(this.table);
  }

  /**
   * yesOrNo格式化函数
   * @param value
   * @param row
   * @param index
   * @returns {any}
   */
  private statusFormat(value,row,index){
    if(value == '0'){
      return "停用";
    }
    if(value == '1'){
      return "正常";
    }
    if(value == '2'){
      return "故障";
    }
  }

  /**
   * yesOrNo格式化函数
   * @param value
   * @param row
   * @param index
   * @returns {any}
   */
  private yesOrNoFormat(value,row,index){
    if(value == '1'){
      return "gprs";
    }
    if(value == '2'){
      return "lora";
    }
    if(value == '3'){
      return "nb";
    }
  }
  /**
   * yesOrNo格式化函数
   * @param value
   * @param row
   * @param index
   * @returns {any}
   */
  private arithmeticTypeFormat(value,row,index){
    if(value == '0'){
      return "设备自测数据";
    }
    if(value == '1'){
      return "设备自测+算法（设备必须有数）";
    }
    if(value == '2'){
      return "设备自测+算法（设备可无数）";
    }
  }

  /**
   * 初始化设备类型，下拉框
   */
  private initMonitorType(){
    this.monitorService.getMonitor().subscribe(
      result => this.responseUtil.success(result ,this.processMonitorResult),
      message => this.responseUtil.error(message)
    )
  }

  /**
   * 处理查询结果
   * @param result
   */
  private processMonitorResult =(result :MsgResult)=>{
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.codMonitors = result.data;
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 初始化时间插件
   */
  initTimeControlConfig(){
    $(".ReceiveTime").daterangepicker({
      // timePickerIncrement: 5,
      singleDatePicker: true,
      timePicker24Hour: true,
      timePicker: true,
      timePickerSeconds: true,

      locale: {
      format: "YYYY-MM-DD H:mm:ss",
        applyLabel: '确定',
        cancelLabel: '取消',
        weekLabel: 'W',
        customRangeLabel: 'Custom Range',
        daysOfWeek: ["日", "一", "二", "三", "四", "五", "六"],
        monthNames: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
        firstDay: 1,
    },
      //设置开始时间，可提前几天。
      startDate: moment().subtract(0,"d").format("YYYY-MM-DD H:mm:ss"),

    });
  }

  /**
   * 选择时间后触发确认按钮获取时间
   * 点击取消按钮回复当前系统时间
   */
  receiveTimeApplyLabel(){
    //绑定确认按钮
    $("#DataReceiveTimePoint").on('apply.daterangepicker',function (){
      this.receiveTimeVal = $("#DataReceiveTimePoint").val();
    }.bind(this));
    //绑定取消按钮
    $("#DataReceiveTimePoint").on('cancel.daterangepicker',function (){
      //回复当前系统时间
      this.initTimeControlConfig();
      //把数据接收时间初始化为空；
      this.receiveTimeVal = '';
    }.bind(this));
  }

  //选择时间后触发重新加载的方法,设备接收时间
  receiveTimeDevApplyLabel(){
    $("#DeviceReceiveTimePoint").on('apply.daterangepicker',function (){
      this.receiveTimeDevVal =  $("#DeviceReceiveTimePoint").val();
    }.bind(this));
    $("#DeviceReceiveTimePoint").on('cancel.daterangepicker',function (){
      this.initTimeControlConfig();
        this.receiveTimeDevVal = '';
    }.bind(this));
  }

  /**
   * 选择导出的数据类型
   */
  // exportDataType() {
  //   $('#exportDataType').find('select').change(function (e) {
  //     console.log($(e.target).val());
  //     console.log(this.table);
  //     this.table.bootstrapTable('destroy');
  //     this.exportType = $(e.target).val();
  //     this.loadSiteMonitor();
  //   }.bind(this));
  // }


  /**
   * 站点设备删除操作
   */
  private siteMonitorDelete(){
    let rows = this.table.bootstrapTable('getSelections');
    this.siteMonitorId=this.tableUtil.getCloumns(rows,"id");
    if ( undefined == this.siteMonitorId || this.siteMonitorId.length == 0 ) {
      this.dialogService.modalInfo("请选择一条数据");
    } else {
      this.dialogService.modalInfoWithCancelBtn("确定删除？", this.requestDelete);
    }
  }

  private requestDelete = () =>{
    if (this.siteMonitorId.length == 1) {
      this.monitorService.siteMonitorDelete(this.siteMonitorId[0]).subscribe(
        result => this.responseUtil.success(result, this.processRoleDeleteResult),
        message => this.responseUtil.error(message)
      );
    } else {
      this.monitorService.siteMonitorDeletes(this.siteMonitorId).subscribe(
        result => this.responseUtil.success(result, this.processRoleDeletesResult),
        message => this.responseUtil.error(message)
      );
    }
  }

  /**
   * 单一删除结果处理
   * @param result
   */
  processRoleDeleteResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.search();
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 批量删除结果处理
   * @param result
   */
  processRoleDeletesResult= (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.search();
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 站点设备修改
   */
  private siteMonitorUpdate(){
    let rows = this.table.bootstrapTable('getSelections');
    this.siteMonitorId = this.tableUtil.getCloumns(rows,"id");
    if (this.siteMonitorId.length != 1) {
      this.dialogService.modalInfo("请选择一条数据");
    } else {
      this.router.navigate(['update',{id:this.siteMonitorId[0]}],{relativeTo :this.route});
    }
  }

  /**
   * 站点设备添加
   */
  private siteMonitorAdd(){
    this.router.navigate(['add'],{relativeTo :this.route});
  }

  /**
   * 设备权重
   */
  private siteDevicePollutant(){
    let rows = this.table.bootstrapTable('getSelections');
    this.snCodeArr = this.tableUtil.getCloumns(rows,"snCode");
    if (this.snCodeArr.length != 1) {
      this.dialogService.modalInfo("请选择一条数据");
    } else {
      this.router.navigate(['pollutant',{snCode:this.snCodeArr[0]}],{relativeTo :this.route});
    }
  }

  /**
   * 为设备分配站点
   */
  private assignmentSite(){
    console.log("分配站点");
    let rows = this.table.bootstrapTable('getSelections');
    if (!rows[0]) {
      return this.dialogService.modalInfo("请选择一条数据!");
    }
    let id = this.tableUtil.getCloumn(rows[0], "id");
    // let snCode = this.tableUtil.getCloumn(rows[0], "snCode");
    if (!!id) {
      console.log(id);
      this.router.navigate(['assign-site', {id: id}], {relativeTo: this.route});
    } else {
      this.dialogService.modalInfo("请选择一条数据!");
    }
  }

}
